#include <iostream>
#include <unistd.h>
#include <cstring>
#include "Comm.hpp"

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage Error: " << "./client  ip   port" << std::endl;
    }
    std::string server_ip = argv[1];
    int server_port = std::stoi(argv[2]);
    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socket error"<<std::endl;
        return 0;
    }
    // 填充网络信息
    struct sockaddr_in server;
    socklen_t serverlen = sizeof(server);
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    // client不需要绑定
    //tcp是面相连接的
    int n = connect(sockfd,CONV(&server),serverlen);
    if (n < 0)
    {
        std::cout<< "connect error"<<std::endl;
        return 0;
    }
    while(true)
    {
        std::string message;
        std::cout<<"input message: ";
        getline(std::cin,message);
        write(sockfd,message.c_str(),message.size());
        char buffer[1024];
        int ret = read(sockfd,buffer,sizeof(buffer)-1);
        if(ret>0)
        {
            buffer[ret] = 0;
            std::cout<<buffer<<std::endl;
        }
    }
    return 0;
}